【发布时间】:2016-02-01 15:50:44
【问题描述】:
我正在将 VBA 翻译成 Google Sheets 脚本,但我不知道如何通过单列障碍中的所有行通过此循环。
我有一列包含 #OrdernNumber、-州代码、名字 和 有时是姓氏,后跟一个空单元格。我需要将名字和姓氏合并到名字单元格中,然后清除下面的姓氏单元格。这在下面的屏幕截图中进行了说明:
屏幕截图中的 C 列和 D 列显示了我用来构建原始 VBA 代码的模式:
Sub WorkingCombineAndClearLoop()
Dim Rngcell As Range
For Each Rngcell In Range("B1:B100")
'if first character is #
If left(Rngcell.Value, 1) <> "#" _
'and if first character is -
And left(Rngcell.Value, 1) <> "-" _
'and if cell is not blank then
And Rngcell.Value <> "" Then
'combine left cell
Rngcell.Value = Rngcell.Offset(0, -1).Value _
'with bottom left cell
& " " & Rngcell.Offset(1, -1).Value
'then clear below cell
Rngcell.Offset(1, 0).ClearContents
End If
Next
End Sub
以下是我带注释的 JavaScript 代码。因为我还不能让循环工作,所以我不得不稍微改变一下代码逻辑:
function workingCombineAndClearNoLoop() {
//get active spreadsheet, sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
//determine row count
var numRows = SpreadsheetApp.getActiveSheet().getRange("A:A").getLastRow();
//if A1's first character is not # AND
if (s.getRange('A1').getValue().substring(0,1) === "#" &&
//if A2's first character is not ' AND
s.getRange('A1').offset(1, 0).getValue().substring(0,1) === "-" ) {
//Set the value of A2 to...
s.getRange('A1').offset(2, 1).setValue(
//A2 cell content + " " + A2 cell content (concatenate)
s.getRange('A1').offset(2, 1).getValue() + " " +
s.getRange('A1').offset(3, 1).getValue())
//and then clear A2
s.getRange('A1').offset(3, 1).clearContent()
};
}
以下是一切都崩溃的地方 - 循环。我只在最后的代码副本中留下了基本内容:
function notWorkingCombineAndClearWithLoop() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var numRows = SpreadsheetApp.getActiveSheet().getRange("A:A").getLastRow();
//loop
//how to replace 'A1' with A[i]?, so that it loops through all cells in the column?
for (var i = 0; i < 25; i++) {
if (s.getRange('A1').getValue().substring(0,1) === "#" &&
s.getRange('A1').offset(1, 0).getValue().substring(0,1) === "-" ) {
s.getRange('A1').offset(2, 1).setValue(
s.getRange('A1').offset(2, 1).getValue() + " " +
s.getRange('A1').offset(3, 1).getValue())
s.getRange('A1').offset(3, 1).clearContent()
}
};
}
注意:我已经完成了 Codacademy 的 JS 课程和几个 Google 表格教程,并且非常擅长 VBA,但我仍然在这个圈子里游来游去。我尝试了许多循环示例,使用变量代替 A1。因为找不到任何可行的解决方案,所以我将无法正常工作的 A1 留作一个简单的占位符。
【问题讨论】:
-
JS 代码看起来不像是 JavaScript。另一方面,代码 sn-ps 并不完整。
-
你是对的。为了简化 VBA 代码,让 JavaScript 用户比 VBA 用户更熟悉它,我把它搞砸了。我整个早上都在编写代码,并且进展缓慢,稳步前进...如果遇到障碍,我将在几个小时内更新此线程:)
-
@Rubén 你觉得这次更新怎么样? :D
-
我添加了语言标签以对每个代码块应用正确的语法突出显示,但在预览中它看起来不起作用。希望修改通过后能正常工作。关于语言标签,见meta.stackexchange.com/questions/184108/…
-
顺便说一句,它看起来越来越好。关于最后一个代码块,Google Apps 脚本显示存在错误(由于额外的
(和缺少}而缺少))。见developers.google.com/apps-script/troubleshooting。
标签: javascript excel vba google-apps-script google-sheets